"""
关键词配置管理页面
用于管理keyword_configs表的Web界面
"""

import os
import sys
from flask import Flask, render_template, request, jsonify, redirect, url_for
import threading
from datetime import datetime

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if project_root not in sys.path:
    sys.path.append(project_root)

from src.utils.video_database import VideoDatabase, KeywordConfig
from src.processors.tikhub_downloader import TikHubDownloader

# 创建Flask应用
app = Flask(__name__, 
            template_folder=os.path.join(project_root, 'src', 'web', 'templates'),
            static_folder=os.path.join(project_root, 'src', 'web', 'static'))

# 初始化数据库
db = VideoDatabase()

def run_keyword_task_in_background(keyword_config):
    """
    在后台线程中执行关键词任务
    
    Args:
        keyword_config: 关键词配置对象
    """
    print(f"[{datetime.now()}] 开始执行关键词任务: {keyword_config.keyword} (数量: {keyword_config.count})，{keyword_config.source_lang}， {keyword_config.target_lang}")
    try:
        # 初始化下载器
        downloader = TikHubDownloader()
        
        # 执行视频收集和处理任务
        # 使用配置中的语言选项
        result = downloader.collect_and_process_videos(
            keyword=keyword_config.keyword,
            count=keyword_config.count,
            platform=keyword_config.platform,
            source_lang=keyword_config.source_lang,
            target_lang=keyword_config.target_lang
        )
        
        # 更新最后运行时间
        db.update_keyword_last_run_time(keyword_config.keyword)
        
        if result["success"]:
            print(f"[{datetime.now()}] 关键词任务执行成功: {keyword_config.keyword}")
            print(f"  - 收集到视频数量: {len(result.get('collected_videos', []))}")
            print(f"  - 实际处理视频数量: {len(result.get('filtered_videos', []))}")
        else:
            print(f"[{datetime.now()}] 关键词任务执行失败: {keyword_config.keyword}")
            print(f"  - 错误信息: {result.get('message', '未知错误')}")
            
    except Exception as e:
        print(f"[{datetime.now()}] 执行关键词任务时出错: {keyword_config.keyword}")
        print(f"  - 错误详情: {e}")
        import traceback
        traceback.print_exc()

@app.route('/')
def index():
    """首页 - 显示关键词配置列表"""
    try:
        configs = db.get_keyword_configs(enabled_only=False)
        return render_template('keyword_configs.html', configs=configs)
    except Exception as e:
        return f"Error: {str(e)}", 500

@app.route('/add', methods=['GET', 'POST'])
def add_config():
    """添加关键词配置"""
    if request.method == 'POST':
        try:
            keyword = request.form.get('keyword', '').strip()
            count = int(request.form.get('count', 5))
            enabled = bool(request.form.get('enabled', False))
            platform = request.form.get('platform', 'douyin').strip()
            source_lang = request.form.get('source_lang', 'zh').strip()
            target_lang = request.form.get('target_lang', 'vi').strip()

            if not keyword:
                return jsonify({'success': False, 'message': '关键词不能为空'}), 400
            
            success = db.add_keyword_config(keyword, count, enabled, platform, source_lang, target_lang)
            if success:
                return jsonify({'success': True, 'message': '添加成功'})
            else:
                return jsonify({'success': False, 'message': '添加失败，关键词可能已存在'}), 400
        except Exception as e:
            return jsonify({'success': False, 'message': f'添加失败: {str(e)}'}), 500
    
    return render_template('add_keyword_config.html')

@app.route('/edit/<int:config_id>', methods=['GET', 'POST'])
def edit_config(config_id):
    """编辑关键词配置"""
    if request.method == 'POST':
        try:
            keyword = request.form.get('keyword', '').strip()
            count = int(request.form.get('count', 5))
            enabled = bool(request.form.get('enabled', False))
            platform = request.form.get('platform', 'douyin').strip()
            source_lang = request.form.get('source_lang', 'zh').strip()
            target_lang = request.form.get('target_lang', 'vi').strip()

            if not keyword:
                return jsonify({'success': False, 'message': '关键词不能为空'}), 400
            
            success = db.update_keyword_config(config_id, keyword=keyword, count=count, 
                                             enabled=enabled, platform=platform,
                                             source_lang=source_lang, target_lang=target_lang)
            if success:
                return jsonify({'success': True, 'message': '更新成功'})
            else:
                return jsonify({'success': False, 'message': '更新失败'}), 400
        except Exception as e:
            return jsonify({'success': False, 'message': f'更新失败: {str(e)}'}), 500
    
    # GET请求 - 显示编辑表单
    try:
        configs = db.get_keyword_configs(enabled_only=False)
        config = next((c for c in configs if c.id == config_id), None)
        if not config:
            return "配置不存在", 404
        return render_template('edit_keyword_config.html', config=config)
    except Exception as e:
        return f"Error: {str(e)}", 500

@app.route('/delete/<int:config_id>', methods=['POST'])
def delete_config(config_id):
    """删除关键词配置"""
    try:
        success = db.delete_keyword_config(config_id)
        if success:
            return jsonify({'success': True, 'message': '删除成功'})
        else:
            return jsonify({'success': False, 'message': '删除失败'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': f'删除失败: {str(e)}'}), 500

@app.route('/trigger/<int:config_id>', methods=['POST'])
def trigger_config(config_id):
    """立即触发关键词配置任务"""
    try:
        # 获取关键词配置
        configs = db.get_keyword_configs(enabled_only=False)
        config = next((c for c in configs if c.id == config_id), None)
        
        if not config:
            return jsonify({'success': False, 'message': '配置不存在'}), 404
            
        if not config.enabled:
            return jsonify({'success': False, 'message': '配置未启用'}), 400
        
        # 在后台线程中执行任务
        thread = threading.Thread(target=run_keyword_task_in_background, args=(config,))
        thread.daemon = True
        thread.start()
        
        return jsonify({'success': True, 'message': '任务已启动'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'触发失败: {str(e)}'}), 500

@app.route('/api/configs')
def api_configs():
    """API接口 - 获取所有关键词配置"""
    try:
        configs = db.get_keyword_configs(enabled_only=False)
        # 转换为字典列表
        config_list = []
        for config in configs:
            config_list.append({
                'id': config.id,
                'keyword': config.keyword,
                'count': config.count,
                'enabled': config.enabled,
                'last_run_time': config.last_run_time,
                'create_time': config.create_time,
                'platform': config.platform,
                'source_lang': config.source_lang,
                'target_lang': config.target_lang
            })
        return jsonify({'success': True, 'data': config_list})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

if __name__ == '__main__':
    # 确保模板目录存在
    template_dir = os.path.join(project_root, 'src', 'web', 'templates')
    if not os.path.exists(template_dir):
        os.makedirs(template_dir)
    
    # 确保静态文件目录存在
    static_dir = os.path.join(project_root, 'src', 'web', 'static')
    if not os.path.exists(static_dir):
        os.makedirs(static_dir)
    
    app.run(debug=True, host='0.0.0.0', port=15001)